import { Slice } from "@reduxjs/toolkit";
import { TypedUseSelectorHook, useDispatch as useReduxDispatch, useSelector as useReduxSelector } from "react-redux";
import { AppDispatch, RootState } from "../index";
type GetArrFirst<T> = T extends [infer Res, ...infer P] ? Res : unknown;

export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector;

export const useDispatch = () => useReduxDispatch<AppDispatch>();

export const useCreateActionFunction = <S extends Slice>(slice: S) => {
	return <T extends keyof S["actions"]>(names: T | T[]) => {
		const dispatch = useDispatch();

		const getItem = (name: T): any => {
			const actionCreator = (slice.actions as S["actions"])[name];
			return (payload: GetArrFirst<Parameters<typeof actionCreator>>) => {
				dispatch(actionCreator(payload));
			};
		};

		if (Array.isArray(names)) {
			return names.map((name: T) => getItem(name));
		}
		return getItem(names);
	};
};
